// 风控流程
import http from '/util/http';
import Config from '/util/config';
const ENUM_RISK_TYPE = {
  IDCARD: '身份证',
  LIVE: '活体',
  SMART: '智能合同',
  AMWITHHOLD: '资金穿透',
  ESIGN: 'e签宝',
};

// 【接入智能合同代扣需求】 https://www.tapd.cn/22046201/prong/stories/view/1122046201001003524
// 开始风控流程
export async function startRisk(orderNo, typeList, successCb, failCb) {
  console.log('startRisk:', orderNo, typeList, successCb);
  if (typeList && typeList.length > 0) {
    let firstType = typeList[0];

    // 判断是否满足补充条件
    if (!firstType) {
      console.error('startRisk firstType is null');
      if (failCb) {
        failCb();
      }
      return;
    }
    // 查询是否可以继续补充资料
    my.showLoading();
    let url = 'order/canContinueSuppleInfo?orderNo=' + orderNo + '&enumType=' + firstType;
    let res = await http.get(url);
    console.log('qureyCanContinueSuppleInfo res = ', res);
    my.hideLoading();

    if (res && res.code == '00') {
      console.log('startRisk goto next.');
    } else {
      my.alert({
        content: res && res.msg,
      });
      if (failCb) {
        failCb();
      }
      return;
    }

    let nextStep = '';
    let nextTypeList = [];
    if (typeList.length > 1) {
      nextStep = typeList[1];
      for (let index = 0; index < typeList.length; index++) {
        const e = typeList[index];
        if (e && index > 0) {
          nextTypeList.push(e);
        }
      }
    }
    console.log('startRisk nextStep = ', nextStep);
    console.log('startRisk nextTypeList = ', nextTypeList);

    if (firstType == 'IDCARD') {
      let tmpStr = JSON.stringify(nextTypeList);
      // 去上传身份证
      my.navigateTo({
        url: '/pages/IDOcr/IDOcr?orderNo=' + orderNo + '&nextStepList=' + tmpStr,
      });
    } else if (firstType == 'LIVE') {
      // 去做活体检测
      let callback = null;
      if (nextStep) {
        callback = function () {
          startRisk(orderNo, nextTypeList, successCb, failCb);
        };
      } else {
        callback = successCb;
      }
      startAPVerify(orderNo, callback, failCb);
    } else if (firstType == 'SMART') {
      // 2020-8-21 增加提示
      my.alert({
        buttonText: '下一步',
        content: '签署时请选择“同意扣款规则并签署”，否则你的订单不会生效且可能会影响后续下单。',
        success: () => {
          // 2020-8-6 智能合同签署
          // 发起手动签署流程
          my.showLoading();
          let redirectUrl =
            'alipays://platformapi/startapp?appId=' +
            Config.appid +
            '&page=pages/orderDetail/orderDetail?orderNo=' +
            orderNo;
          console.log('startHandsignFlow redirectUrl = ', redirectUrl);
          let params = {
            orderNo: orderNo,
            redirectUrl: redirectUrl,
          };
          // url = 'aliSmartCon/startHandsignFlow';
          // res = await http.post(url, params);

          http
            .post('aliSmartCon/startHandsignFlow', params)
            .then((res) => {
              console.log('startHandsignFlow res = ', res);
              my.hideLoading();

              if (res && res.code === '00') {
                console.log('startRisk goto HandsignFlow.');
                let flowId = res.data.flowId;
                let signUrl = decodeURIComponent(res.data.url);
                console.log('signUrl = ' + signUrl);
                let appId = signUrl.split('appId=')[1].split('&page=')[0];
                let page = signUrl.split('page=')[1].split('&query=')[0];
                let query = signUrl.split('&query=')[1];
                let path = page + '?' + query;
                console.log('page = ' + page);
                console.log('appId = ' + appId);
                console.log('query = ' + query);
                console.log('path = ' + path);
                // let path = signUrl.split('page=')[1];
                // let extraData = signUrl.split('query=')[1];
                // console.log('extraData = ' + extraData);
                setFlowId(flowId);
                my.navigateToMiniProgram({
                  // appId: '2021001152620480',
                  // path: 'pages/signH5/index?' + extraData,
                  appId: appId,
                  path: path,
                  // extraData: extraData,
                  success: (res) => {
                    console.log('navigateToMiniProgram ok.' + JSON.stringify(res));
                  },
                  fail: (res) => {
                    console.log('navigateToMiniProgram fail.' + JSON.stringify(res));
                    setFlowId('');
                  },
                });
              } else {
                my.alert({
                  content: res && res.msg,
                });
                if (failCb) {
                  failCb();
                }
                return;
              }
            })
            .catch((err) => {
              console.log('uploadFormId err = ', err);
            });
        },
      });
    } else if (firstType == 'AMWITHHOLD') {
      my.showLoading();
      let params = {
        orderNo: orderNo,
      };
      http
        .post('definAsset/createUserSignAuth', params)
        .then((res) => {
          console.log('createUserSignAuth res = ', res);
          my.hideLoading();
          if (res && res.code === '00' && res.data) {
            const url = encodeURIComponent(res.data);
            my.paySignCenter({
              signStr: url,
              success: (res) => {
                console.log('createUserSignAuth signRes', JSON.stringify(res));
                let result = '签约成功!';
                if (res.resultStatus !== '7000') {
                  switch (res.resultStatus) {
                    case '6001':
                      result = '用户中途取消';
                      break;
                    case '6002':
                      result = '网络连接错误';
                      break;
                    case '7001':
                      result = '签约结果未知';
                      break;
                    default:
                      result = '协约签约失败' + res.resultStatus;
                      break;
                  }
                  my.alert({
                    content: result,
                  });
                  if (failCb) {
                    failCb();
                  }
                } else {
                  console.log('前端小程序返回成功签署资金穿透代扣');
                  let callback = null;
                  if (nextStep) {
                    callback = function () {
                      startRisk(orderNo, nextTypeList, successCb, failCb);
                    };
                  } else {
                    callback = successCb;
                  }
                  qureyAuthSignedResult(orderNo, callback, failCb);
                }
              },
              fail: (res) => {
                my.alert({
                  title: 'fail',
                  content: JSON.stringify(res),
                });
              },
            });
            //
          } else if (res && res.code === '00') {
            console.log('签署资金穿透代扣授权,发起请求竟然以前签约过了');
            let callback = null;
            if (nextStep) {
              callback = function () {
                startRisk(orderNo, nextTypeList, successCb, failCb);
              };
            } else {
              callback = successCb;
            }
            if (callback) {
              callback();
            }
          } else {
            my.alert({
              content: res.msg,
            });
            if (failCb) {
              failCb();
            }
            return;
          }
        })
        .catch((err) => {
          my.alert({
            content: err,
          });
        });
    } else if (firstType == 'ESIGN') {
      //POST /esign/startHandsignFlow   e签宝签署合同
      my.alert({
        buttonText: '下一步',
        content: '请仔细阅读并签署合同，否则你的订单不会生效且可能会影响后续下单。',
        success: () => {
          // 2020-8-6 智能合同签署
          // 发起手动签署流程
          my.showLoading();
          let redirectUrl =
            'alipays://platformapi/startapp?appId=' +
            Config.appid +
            '&page=pages/orderDetail/orderDetail?orderNo=' +
            orderNo;
          console.log('startHandsignFlow redirectUrl = ', redirectUrl);
          let params = {
            channelNo: Config.channelNo,
            orderNo: orderNo,
            redirectUrl: redirectUrl,
          };
          http
            .post('esign/startHandsignFlow', params)
            .then((res) => {
              console.log('startHandsignFlow res = ', res);
              my.hideLoading();
              if (res && res.code === '00') {
                let flowId = res.data.flowId;
                let signerId = res.data.signerId;
                let env = Config.env;
                let thirdPartyUserId = res.data.thirdPartyUserId;
                let skipResult = true;
                let skipGuide = true;
                my.navigateTo({
                  url: `plugin://esign/esign?env=${env}&flowId=${flowId}&signerId=${signerId}&thirdPartyUserId=${thirdPartyUserId}&skipResult=${skipResult}&skipGuide=${skipGuide}`,
                });
                setEsignFlowId(flowId);
                setNextStepList(nextTypeList);
              } else {
                my.alert({
                  content: res && res.msg,
                });
                if (failCb) {
                  failCb();
                }
                return;
              }
            })
            .catch((err) => {
              console.log('uploadFormId err = ', err);
            });
        },
      });
    }
  } else {
    if (successCb) {
      successCb();
    }
  }
}

// 支付宝小程序刷脸接入
// https://tech.antfin.com/docs/2/170144
export function startAPVerify(orderNo, successCb, failCb) {
  my.showLoading();
  let params = {
    orderNo: orderNo,
  };
  http
    .post('alilivenessCheck/preCheckAliLivenessCheck', params)
    .then((res) => {
      console.log('uploadFormId res = ', res);
      if (res && res.code == '00') {
        let options = {
          certifyId: res.data.certifyId,
          url: res.data.certifyUrl,
        };
        my.call(
          'startBizService',
          {
            name: 'open-certify',
            param: JSON.stringify(options),
          },
          function (verifyResult) {
            my.hideLoading();
            console.log('verifyResult = ', verifyResult);
            // 认证结果回调触发, 以下处理逻辑为示例代码，开发者可根据自身业务特性来自行处理
            if (verifyResult.resultStatus === '9000') {
              // 验证成功，接入方在此处处理后续的业务逻辑
              let certifyId = verifyResult.result.certifyId;
              qureyAPVerifyResult(certifyId, successCb, failCb);
              return;
            } else {
              // 用户主动取消认证
              if (verifyResult.resultStatus === '6001') {
                // 可做下 toast 弱提示
                my.showToast({
                  content: '你已取消身份认证',
                });
              } else {
                my.showToast({
                  content: '身份认证失败',
                });
              }
              if (failCb) {
                failCb();
              }
              // const errorCode = verifyResult.result && verifyResult.result.errorCode;
              // 其他结果状态码判断和处理 ...
            }
          },
        );
      } else {
        my.hideLoading();
        my.showToast({
          content: res && res.msg,
        });
        if (failCb) {
          failCb();
        }
      }
    })
    .catch((err) => {
      console.log('uploadFormId err = ', err);
    });
}

function qureyAuthSignedResult(orderNo, successCb, failCb) {
  my.showLoading();
  console.log('qureyAuthSignedResult ', orderNo);
  let params = {
    orderNo: orderNo,
  };
  http
    .post('definAsset/checkHasAuthForOrderCheck', params)
    .then((res) => {
      console.log('qureyAuthSignedResult res = ', res);
      my.hideLoading();
      if (res && res.code === '00') {
        if (successCb) {
          successCb();
        }
      } else {
        my.alert({
          content: res && res.msg,
        });
        if (failCb) {
          failCb();
        }
        return;
      }
    })
    .catch((err) => {
      console.log('qureyAuthSignedResult err = ', err);
    });
}

function qureyAPVerifyResult(certifyId, successCb, failCb) {
  my.showLoading();
  http
    .get('alilivenessCheck/queryAliLivenessCheckResult?certifyId=' + certifyId)
    .then((res) => {
      console.log('qureyAPVerifyResult res = ', res);
      my.hideLoading();
      if (res && res.code === '00') {
        if (successCb) {
          successCb();
        }
      } else {
        my.showToast({
          content: res && res.msg,
        });
        if (failCb) {
          failCb();
        }
      }
    })
    .catch((err) => {
      console.log('qureyAPVerifyResult err = ', err);
      if (failCb) {
        failCb();
      }
    });
}

// 查询代扣规则签署结果
export function queryContractPayrules(flowId, successCb, failCb) {
  console.log('queryContractPayrules flowId = ' + flowId);
  my.showLoading();
  http
    .get('aliSmartCon/queryContractPayrules?flowId=' + flowId)
    .then((res) => {
      console.log('queryContractPayrules res = ', res);
      my.hideLoading();
      if (res && res.code === '00') {
        console.log('queryContractPayrules succ');
        if (successCb) {
          successCb();
        }
      } else {
        my.alert({
          // content: res && res.msg
          content: '区块链合同签署失败',
        });
        if (failCb) {
          failCb();
        }
      }
    })
    .catch((err) => {
      console.log('queryContractPayrules err = ', err);
    });
}

// 查询合同签署状态  esign/eSignQueryByFlowld/{flowld}
export function getContractStates(orderNo, flowId, nextStepList, successCb, failCb) {
  let that = this;
  my.showLoading();
  if (!flowId) {
    my.hideLoading();
    return;
  }
  console.log('getContractStates-->', orderNo, flowId, nextStepList, successCb, failCb);
  let url = 'esign/eSignQueryByFlowld/' + flowId;
  http.get(url).then((res) => {
    console.log('eSignQueryByFlowld', res);
    if (res && res.code === '00') {
      my.hideLoading();
      if (nextStepList) {
        startRisk(orderNo, nextStepList, successCb, failCb);
      } else {
        console.log('getContractStates0--成功回调1');
        if (successCb) {
          console.log('getContractStates0--成功回调2');
          successCb();
        }
      }
    } else {
      if (failCb) {
        failCb(orderNo);
      }
    }
  });
}

export function setFlowId(flowId) {
  my.setStorageSync({
    key: 'aliSmartFlowId',
    data: flowId
  });
}

export function getFlowId() {
  let flowId = '';
  let storeRes = my.getStorageSync({ key: 'aliSmartFlowId' }); // undefined or {}
  if (storeRes) {
    flowId = storeRes.data;
  }
  return flowId;
}

export function setEsignFlowId(flowId) {
  my.setStorage({
    key: 'eSignFlowId',
    data: flowId,
    success: function () {},
    fail: function (error) {
      console.log('setStorage flowId error:', error);
    },
  });
}

export function getEsignFlowId() {
  let flowId = '';
  let storeRes = my.getStorageSync({ key: 'eSignFlowId' }); // undefined or {}
  if (storeRes) {
    flowId = storeRes.data;
  }
  return flowId;
}

export function setNextStepList(nextStepList) {
  my.setStorage({
    key: 'nextStepList',
    data: nextStepList,
    success: function () {},
    fail: function (error) {
      console.log('setStorage nextStepList error:', error);
    },
  });
}

export function getNextStepList() {
  let nextStepList = '';
  let storeRes = my.getStorageSync({ key: 'nextStepList' }); // undefined or {}
  if (storeRes) {
    nextStepList = storeRes.data;
  }
  return nextStepList;
}
